import React, { useMemo, useState } from 'react';
import { 
  Card, 
  Spin, 
  Typography, 
  Button,
  Space,
  Alert,
  message
} from 'antd';
import {
  ExperimentOutlined,
  PlayCircleOutlined,
  InfoCircleOutlined,
  CheckOutlined,
  RobotOutlined
} from '@ant-design/icons';
import { useAnalysisContext, useAnalysisActions } from '../../context/AnalysisContext';
import EnhancedProblemTable from './EnhancedProblemTable';
import { UnifiedProblemData } from '../../types/analysis';
import { convertLegacyProblemsToUnified, generateMockAIProblems } from '../../utils/problemDataConverter';
import './AnalysisResults.css';

const { Text } = Typography;

const UnifiedAiAnalysisResults: React.FC = () => {
  const { state } = useAnalysisContext();
  const actions = useAnalysisActions();
  const [mockAIEnabled, setMockAIEnabled] = useState(true); // 临时开关，用于测试

  const {
    analysisResult,
    isAnalyzing,
    sqlContent,
    sourceDbType,
    targetDbType,
    selectedIssueId
  } = state;

  // 生成统一的问题数据
  const unifiedProblems = useMemo((): UnifiedProblemData[] => {
    let problems: UnifiedProblemData[] = [];

    // 如果有真实的分析结果，使用真实数据
    if (analysisResult?.issues) {
      // 将现有的issues转换为分组格式，然后转换为统一格式
      const mockGroups = [
        {
          key: 'AI_ISSUES',
          title: 'AI识别问题',
          icon: <RobotOutlined />,
          count: analysisResult.issues.length,
          items: analysisResult.issues.map(issue => ({
            id: issue.id,
            lineNumber: issue.lineNumber,
            columnNumber: issue.columnNumber,
            severity: issue.severity as any,
            category: issue.category,
            description: issue.description,
            suggestion: issue.suggestion,
            ruleName: issue.ruleName,
            originalCode: issue.originalCode,
            suggestedCode: issue.suggestedCode,
            sqlFragment: issue.sqlFragment
          })),
          color: '#722ed1'
        }
      ];
      
      problems = convertLegacyProblemsToUnified(mockGroups, 'LLM');
    } 
    // 临时：如果没有真实数据且启用了mock，生成模拟数据
    else if (mockAIEnabled && sqlContent.trim()) {
      problems = generateMockAIProblems(sqlContent);
    }

    return problems;
  }, [analysisResult, sqlContent, mockAIEnabled]);

  // 计算统计数据
  const statistics = useMemo(() => {
    return {
      total: unifiedProblems.length,
      high: unifiedProblems.filter(p => p.severity === 'HIGH').length,
      medium: unifiedProblems.filter(p => p.severity === 'MEDIUM').length,
      low: unifiedProblems.filter(p => p.severity === 'LOW').length,
      info: unifiedProblems.filter(p => p.severity === 'INFO').length,
      avgConfidence: unifiedProblems.length > 0 
        ? Math.round(unifiedProblems.reduce((sum, p) => sum + (p.confidence || 0), 0) / unifiedProblems.length)
        : 0
    };
  }, [unifiedProblems]);

  // 处理问题点击
  const handleIssueClick = (issue: UnifiedProblemData) => {
    actions.setSelectedIssueId(issue.id);
    actions.setCursorPosition({ 
      line: issue.lineNumber, 
      column: issue.columnNumber 
    });
  };

  // 处理应用建议
  const handleApplySuggestion = (issue: UnifiedProblemData) => {
    if (!issue.suggestedCode) {
      message.warning('该问题没有优化建议');
      return;
    }

    // 这里需要实现将建议应用到编辑器的逻辑
    // 暂时使用简单的替换逻辑
    const newSqlContent = sqlContent.replace(
      issue.originalCode || issue.sqlFragment || '',
      issue.suggestedCode
    );
    
    actions.setSqlContent(newSqlContent);
    message.success(`已应用SQL#${issue.statementNumber}的优化建议`);
  };

  // 处理批量应用
  const handleBatchApply = (issues: UnifiedProblemData[]) => {
    let newSqlContent = sqlContent;
    
    // 按SQL语句编号排序，确保正确的应用顺序
    const sortedIssues = [...issues].sort((a, b) => a.statementNumber - b.statementNumber);
    
    sortedIssues.forEach(issue => {
      if (issue.suggestedCode && (issue.originalCode || issue.sqlFragment)) {
        newSqlContent = newSqlContent.replace(
          issue.originalCode || issue.sqlFragment || '',
          issue.suggestedCode
        );
      }
    });
    
    actions.setSqlContent(newSqlContent);
    message.success(`已批量应用 ${issues.length} 个优化建议`);
  };

  // 渲染空状态
  const renderEmptyState = () => {
    if (!sqlContent.trim()) {
      return (
        <div className="analysis-empty">
          <div className="analysis-empty-icon">
            <ExperimentOutlined />
          </div>
          <div className="analysis-empty-text">
            请在左侧编辑器中输入SQL语句
          </div>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            AI将智能分析您的SQL并提供优化建议
          </Text>
        </div>
      );
    }

    if (sourceDbType === targetDbType) {
      return (
        <div className="analysis-empty">
          <div className="analysis-empty-icon">
            <InfoCircleOutlined />
          </div>
          <div className="analysis-empty-text">
            源数据库和目标数据库相同
          </div>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            请选择不同的数据库类型进行AI分析
          </Text>
        </div>
      );
    }

    return (
      <div className="analysis-empty">
        <div className="analysis-empty-icon">
          <PlayCircleOutlined />
        </div>
        <div className="analysis-empty-text">
          点击"AI分析"按钮开始分析
        </div>
        <Text type="secondary" style={{ fontSize: '12px' }}>
          AI将智能识别兼容性问题并提供优化方案
        </Text>
      </div>
    );
  };

  // 渲染成功状态
  const renderSuccessState = () => (
    <div className="analysis-empty">
      <div className="analysis-empty-icon" style={{ color: '#52c41a' }}>
        <CheckOutlined />
      </div>
      <div className="analysis-empty-text">
        AI分析完成，未发现兼容性问题
      </div>
      <Text type="secondary" style={{ fontSize: '12px' }}>
        您的SQL语句在目标数据库中兼容性良好
      </Text>
    </div>
  );

  return (
    <Card 
      className="results-section ai-analysis-results"
      title={
        <Space>
          <ExperimentOutlined />
          <span>AI分析结果</span>
          {isAnalyzing && <Spin size="small" />}
          {statistics.avgConfidence > 0 && (
            <Text type="secondary" style={{ fontSize: '12px' }}>
              平均置信度: {statistics.avgConfidence}%
            </Text>
          )}
        </Space>
      }
      size="small"
      extra={
        mockAIEnabled && (
          <Button 
            size="small" 
            type="link"
            onClick={() => setMockAIEnabled(!mockAIEnabled)}
          >
            {mockAIEnabled ? '关闭模拟' : '启用模拟'}
          </Button>
        )
      }
    >
      {isAnalyzing ? (
        <div className="analysis-loading">
          <Spin size="large" />
          <div style={{ marginTop: 16, textAlign: 'center' }}>
            <Text>AI正在分析您的SQL...</Text>
            <br />
            <Text type="secondary" style={{ fontSize: '12px' }}>
              这可能需要几秒钟时间
            </Text>
          </div>
        </div>
      ) : unifiedProblems.length > 0 ? (
        <div>
          {statistics.total > 0 && (
            <Alert
              message={`AI识别到 ${statistics.total} 个潜在问题`}
              description={
                <div>
                  <span>高危: {statistics.high}个, 中危: {statistics.medium}个, 低危: {statistics.low}个</span>
                  {statistics.avgConfidence > 0 && (
                    <span style={{ marginLeft: 16 }}>
                      平均置信度: {statistics.avgConfidence}%
                    </span>
                  )}
                </div>
              }
              type={statistics.high > 0 ? 'error' : statistics.medium > 0 ? 'warning' : 'info'}
              showIcon
              style={{ marginBottom: 16 }}
            />
          )}
          
          <EnhancedProblemTable
            problems={unifiedProblems}
            selectedIssueId={selectedIssueId}
            onIssueClick={handleIssueClick}
            onApplySuggestion={handleApplySuggestion}
            onBatchApply={handleBatchApply}
            height={600}
            taskConfig={{ taskType: 'MANUAL_SQL' }} // 手动SQL分析默认配置
          />
        </div>
      ) : (
        analysisResult ? renderSuccessState() : renderEmptyState()
      )}
    </Card>
  );
};

export default UnifiedAiAnalysisResults;